import fs from "node:fs";
import { NodeSSH } from "node-ssh";
import { configDotenv } from "dotenv";
import { resolve } from "node:path";
import { readJSONSync, pathExistsSync } from "fs-extra/esm";
import { getCurrentBranchName } from "./currentBranch.js";

const currentBranch = getCurrentBranchName();
if (currentBranch !== "master") {
  console.error('请切换到 "master" 分支');
  process.exit(-1);
}

const __dirname = resolve();

const dist = resolve(__dirname, ".vitepress/dist");

if (!pathExistsSync(dist)) {
  console.error(`${dist} 不存在`);
  process.exit(-1);
}

const name = readJSONSync(resolve(__dirname, "package.json")).name;

const privateKeyPath = configDotenv({ path: "./.env" }).parsed.privateKeyPath;
if (!privateKeyPath) {
  throw new Error(".env文件不存在");
}

const ssh = new NodeSSH();

ssh
  .connect({
    username: "root",
    host: "0230812.xyz",
    privateKey: fs.readFileSync(privateKeyPath).toString(),
  })
  .then(success => {
    // 上传之前删除
    ssh.execCommand(`rm -rf /usr/local/kaijia-web/${name}`).then(() => {
      // Putting entire directories
      const failed = [];
      const successful = [];
      ssh
        .putDirectory(dist, `/usr/local/kaijia-web/${name}/dist/`, {
          recursive: true,
          concurrency: 2,
          // ^ WARNING: Not all servers support high concurrency
          // try a bunch of values and see what works on your server
          tick: function (localPath, remotePath, error) {
            if (error) {
              failed.push(localPath);
            } else {
              successful.push(localPath);
            }
          },
        })

        .then(function (status) {
          console.log(status ? "上传成功" : "上传失败");
          ssh.dispose();
        });
    });
  });
